package o2o.web.actions.agent;

import com.jinyou.utils.common.AjaxResult;
import com.jinyou.utils.common.DateUtils;
import com.jinyou.utils.common.Geohash;
import com.jinyou.utils.common.ValidateUtil;
import o2o.cache.agent.CityAgentAddressMemory;
import o2o.cache.user.UserInfoMemory;
import o2o.cache.user.UserOnlineImpl;
import o2o.config.dao.UserDaoSql;
import o2o.dao.PO.PojoTables;
import o2o.dao.PO.agent.CityAgentAddress;
import o2o.dao.PO.user.UserInfo;
import o2o.dao.VO.agent.CityAgentAddressVO;
import o2o.web.actions.user.User;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

//城市代理
@Controller
public class CityAgentAddressAction {

    //获取代理地址列表(楼号)
    @RequestMapping(method = RequestMethod.POST, value = "/user/agent/address/list")
    @ResponseBody
    public String agent_list(Long agentId, Long shopId, String province, String city, String county, String content) {
        if (ValidateUtil.isNotID(agentId) && ValidateUtil.isNotID(shopId)) {
            return AjaxResult.errorResult("学校或者店铺不能为空");
        }
        List<CityAgentAddressVO> list = null;
        if (ValidateUtil.isID(shopId)) {
            list = this.listOfShopId(shopId, province, city, county);
        } else {
            list = CityAgentAddressMemory.getInstance().listOfAgentId(agentId);
        }
        if (ValidateUtil.isAbsList(list) && ValidateUtil.isNotNull(content)) {
            list = list.stream().filter(item -> {
                if (ValidateUtil.isNull(item.getAddress()) || !item.getAddress().contains(content)) {
                    return false;
                }
                return true;
            }).collect(Collectors.toList());
        }
        if (ValidateUtil.isAbsList(list)) {
            try {
                Collections.sort(list, new Comparator<CityAgentAddressVO>() {
                    public int compare(CityAgentAddressVO arg0, CityAgentAddressVO arg1) {
                        return arg0.getOrderNo().compareTo(arg1.getOrderNo());//按距离排序
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
            return AjaxResult.successResult(list.size(), list);
        }
        return AjaxResult.successResult(0, null);
    }

    //根据上级获取地址信息
    @RequestMapping(method = RequestMethod.POST, value = "/user/agent/address/child/list")
    @ResponseBody
    public String agent_child_list(Long agentId, Long pId) {
        if (null == pId) {
            pId = -1l;
        }
        List<CityAgentAddressVO> list = CityAgentAddressMemory.getInstance().listOfPid(pId);
        if (ValidateUtil.isAbsList(list)) {
            try {
                Collections.sort(list, new Comparator<CityAgentAddressVO>() {
                    public int compare(CityAgentAddressVO arg0, CityAgentAddressVO arg1) {
                        return arg0.getOrderNo().compareTo(arg1.getOrderNo());//按距离排序
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
            return AjaxResult.successResult(list.size(), list);
        }

        return AjaxResult.successResult(0, null);
    }

    //添加楼号--管理端
    @RequestMapping(method = RequestMethod.POST, value = "/agent/address/add")
    @ResponseBody
    public String agent_add(String token, CityAgentAddress info) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        //验证是否有登录权限C
        if (!User.getInstance().hasShopAuth(user.getUsername(), user.getUserType())) {
            return AjaxResult.errorResult("您没有权限");
        }

        if (ValidateUtil.isNotID(info.getAgentId()) && ValidateUtil.isNotID(info.getShopId())) {
            return AjaxResult.errorResult("信息不完整,请查证");
        }

        Long time = DateUtils.getCurrTime();
        info.setCreateUser(user.getUsername());
        info.setCreateTime(time);
        info.setDelFlag(0);
        info.setId(null);

        if (null == info.getpId()) {
            info.setpId(-1l);
        }

        if (ValidateUtil.isAbsDouble(info.getLat()) || ValidateUtil.isAbsDouble(info.getLng())) {
            String geocode = Geohash.encode(info.getLat(), info.getLng());
            Long areaPoint = Geohash.getArea(info.getLat(), info.getLng());
            info.setGeocode(geocode);
            info.setAreaPoint(areaPoint);
        }


        try {
            UserDaoSql.getInstance().insertObj(PojoTables.CITY_AGENT_ADDRESS, info);
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("添加代理失败，请稍后再试");
        }

        CityAgentAddressMemory.getInstance().add(time);

        return AjaxResult.successResult();
    }

    //修改楼号--管理端
    @RequestMapping(method = RequestMethod.POST, value = "/agent/address/modify")
    @ResponseBody
    public String agent_modify(String token, CityAgentAddress info) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        //验证是否有登录权限
        if (!User.getInstance().hasShopAuth(user.getUsername(), user.getUserType())) {
            return AjaxResult.errorResult("您没有权限");
        }

        if (ValidateUtil.isNotID(info.getId())) {
            return AjaxResult.errorResult("请选择要修改的");
        }

        String latlng = "";
        //修改学校代理
        if (ValidateUtil.isAbsDouble(info.getLat()) || ValidateUtil.isAbsDouble(info.getLng())) {
            String geocode = Geohash.encode(info.getLat(), info.getLng());
            Long areaPoint = Geohash.getArea(info.getLat(), info.getLng());
            latlng = ",lat=" + info.getLat() + ",lng=" + info.getLng() + ",geocode='" + geocode + "',areaPoint=" + areaPoint;
        }

        String cityStr = "";
        if (ValidateUtil.isNotNull(info.getCity())) {
            if (ValidateUtil.isNotNull(info.getProvince())) {
                cityStr += ", province = '" + info.getProvince() + "' ";
            }
            cityStr += ", city = '" + info.getCity() + "' ";
            cityStr += ", county = '" + (ValidateUtil.isNull(info.getCounty()) ? "" : info.getCounty()) + "' ";
        }
        String extra1 = "";
        if (null != info.getExtra1()) {
            extra1 = ",extra1='" + info.getExtra1() + "'";
        }
        String extra2 = "";
        if (null != info.getExtra2()) {
            extra2 = ",extra2='" + info.getExtra2() + "'";
        }
        String extra3 = "";
        if (null != info.getExtra3()) {
            extra3 = ",extra3='" + info.getExtra3() + "'";
        }
        String orderNo = "";
        if (null != info.getOrderNo()) {
            orderNo = ",orderNo=" + info.getOrderNo();
        }

        StringBuffer sb = new StringBuffer();
        sb.append("update ").append(PojoTables.CITY_AGENT_ADDRESS).append(" set name='").append(info.getName()).append("',address='").append(info.getAddress())
                .append("',updateUser='").append(user.getUsername()).append("'")
                .append(latlng)
                .append(cityStr)
                .append(extra1).append(extra2).append(extra3)
                .append(orderNo)
                .append(" where delFlag = 0 and id = ").append(info.getId());

        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("修改失败，请稍后再试");
        }

        CityAgentAddressMemory.getInstance().modifyById(info.getId());

        return AjaxResult.successResult();
    }

    //删除代理--管理端
    @RequestMapping(method = RequestMethod.POST, value = "/agent/address/delete")
    @ResponseBody
    public String agent_delete(String token, String ids) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        //验证是否有登录权限
        if (!User.getInstance().hasShopAuth(user.getUsername(), user.getUserType())) {
            return AjaxResult.errorResult("您没有权限");
        }

        if (ValidateUtil.isNull(ids)) {
            return AjaxResult.errorResult("请选择要删除的");
        }

        StringBuffer sb = new StringBuffer();
        sb.append("update ").append(PojoTables.CITY_AGENT_ADDRESS).append(" set delFlag = 1 ,updateUser = '").append(user.getUsername())
                .append("' where delFlag = 0 and id in (").append(ids).append(")");
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("删除失败，请稍后再试");
        }
        try {
            String[] idArr = ids.split(",");
            if (null != idArr) {
                for (int i = 0; i < idArr.length; i++) {
                    if (ValidateUtil.isNull(idArr[i])) {
                        continue;
                    }
                    Long id = Long.parseLong(idArr[i]);
                    if (ValidateUtil.isNotID(id)) {
                        continue;
                    }
                    CityAgentAddressMemory.getInstance().deleteById(id);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return AjaxResult.successResult();
    }


    private List<CityAgentAddressVO> listOfShopId(Long shopId, String province, String city, String county) {
        if (ValidateUtil.isNotID(shopId)) {
            return Collections.emptyList();
        }
        List<CityAgentAddress> cityAgentAddresses = CityAgentAddressMemory.getInstance().findByShopId(shopId);
        if (!ValidateUtil.isAbsList(cityAgentAddresses)) {
            return Collections.emptyList();
        }
        List<CityAgentAddressVO> voList = new ArrayList<>();
        for (CityAgentAddress agentAddress : cityAgentAddresses) {
            if (ValidateUtil.isNotNull(province) && !province.equals(agentAddress.getProvince())) {
                continue;
            }
            if (ValidateUtil.isNotNull(city) && !city.equals(agentAddress.getCity())) {
                continue;
            }
            if (ValidateUtil.isNotNull(county) && !county.equals(agentAddress.getCounty())) {
                continue;
            }
            CityAgentAddressVO vo = new CityAgentAddressVO();
            BeanUtils.copyProperties(agentAddress, vo);
            voList.add(vo);
        }
        return voList;
    }


}
